package com.yyge.mapper.impl;

import com.yyge.entity.Rolr;
import com.yyge.mapper.RolrMapper;
import com.yyge.util.DruidDataSourceHandler;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.ResultSetHandler;
import org.apache.commons.dbutils.handlers.BeanHandler;

import javax.sql.DataSource;
import java.awt.peer.RobotPeer;
import java.sql.SQLException;

public class RolrMapperImpl implements RolrMapper {
    @Override
    public int insert(Rolr rolr) {
        // 得到连接池
        DataSource dataSource = DruidDataSourceHandler.getDataSource();
         // 基于QueryRunner类的对象来进行
        QueryRunner queryRunner=new QueryRunner(dataSource);
        String sql="insert into role"+
                " (roleId, roleName)"+
                "values (?,?)";
        Object[] params={
                rolr.getRolrid(),
                rolr.getRoleName()
        };
        try {
           return queryRunner.update(sql,params);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public int deleteByPrimaryKey(Integer key) {
        String sql="delete from role where roleId=?";
        DataSource dataSource=DruidDataSourceHandler.getDataSource();
        QueryRunner queryRunner=new QueryRunner(dataSource);
        try {
            return queryRunner.update(sql,key);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public int updateByPrimaryKey(Rolr rolr) {
        String sql="update role set "+
           "roleName=?"+
           "where roleId=?";
        DataSource dataSource=DruidDataSourceHandler.getDataSource();
        QueryRunner queryRunner=new QueryRunner(dataSource);
        Object[] params= {
            rolr.getRoleName(),
            rolr.getRolrid(),

        };
        try {
           return queryRunner.update(sql,params);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public Rolr selectByPrimaryKey(Integer key) {
        String sql="select * from role where roleId=?";
        QueryRunner queryRunner=new QueryRunner(DruidDataSourceHandler.getDataSource());
        ResultSetHandler<Rolr> rsh= new BeanHandler<>(Rolr.class);
        try {
            Rolr addrInfo=queryRunner.query(sql,rsh,key);
            return addrInfo;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}
